/** 
 *Copyright(C) 2018 by #COMPANY# 
 *All rights reserved. 
 *FileName:     #SCRIPTFULLNAME# 
 *Author:       #AUTHOR# 
 *Version:      #VERSION# 
 *UnityVersion：#UNITYVERSION# 
 *Date:         #DATE# 
 *Description:    
 *History: 
 */

using System;

using UnityEngine;

// 移动画类
public class MoveTween : MonoBehaviour {

    // 开始坐标
    public Vector3 fromPosition;

    // 终点坐标
    public Vector3 toPosition;

    // 间隔
    public float duration;

    // 发生动画flag
    private bool isTween;

    // 经过时间
    private float elapsedTime;

    // 结束回调匿名函数
    private Action endCallBack;

    //-------------------------------------------------------
    // MonoBehaviour Function
    //-------------------------------------------------------
    // 动画的更新处理
    private void Update ( ) {

        if (!isTween) {
            return;
        }

        // 动画开始到结束的经过时间
        elapsedTime += Time.deltaTime;

        if (elapsedTime >= duration) {
            // 动画结束的处理
            transform.position = toPosition;
            isTween = false;
            if (endCallBack != null) {
                endCallBack ( );
            }
            Destroy (this);
            return;
        }

        // 移动进度
        var moveProgress = elapsedTime / duration;
        transform.position = Vector3.Lerp (fromPosition, toPosition, moveProgress);
    }

    //-------------------------------------------------------
    // Public Function
    //-------------------------------------------------------
    // 动画开始处理
    public void DoTween (Vector3 from, Vector3 to, float dur, Action endcb) {
        fromPosition = from;
        toPosition = to;
        duration = dur;
        endCallBack = endcb;

        transform.position = from;
        elapsedTime = 0;
        isTween = true;
    }
}
